package com.livi.security.config.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.livi.security.mapper.sys.SysPermissionMapper;
import com.livi.security.mapper.sys.SysUserMapper;
import com.livi.security.model.sys.SysPermission;
import com.livi.security.model.sys.SysUser;

public class CustomUserDetailsService implements UserDetailsService {
	@Autowired
	SysUserMapper sysUserMapper;
	@Autowired
	private SysPermissionMapper sysPermissionMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser sysUser = sysUserMapper.selectByAccount(username);
		if (sysUser == null)
			throw new UsernameNotFoundException("User " + username + " was not found in db");
		List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
		// 获取该用户所拥有的权限
		List<SysPermission> sysPermissions = sysPermissionMapper.selectListByUserId(sysUser.getUserId());
		// 声明用户授权
		sysPermissions.forEach(sysPermission -> {
			GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getPermissionSource());
			grantedAuthorities.add(grantedAuthority);
		});
		return new User(sysUser.getUserId().toString(), sysUser.getPassword(), sysUser.getEnabled(), true, sysUser.getExpired(),
				sysUser.getLocked(), grantedAuthorities);
	}

}
